package com.example.s.utils;

import androidx.lifecycle.MutableLiveData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class LiveDataBus {
    private static LiveDataBus liveDataBus;
    private Map<String, MutableLiveData<Object>> map;
    private MutableLiveData<Object> objectMutableLiveData;

    private LiveDataBus() {
        this.map = new HashMap<>();
    }

    public static synchronized LiveDataBus getInstance() {
        if (liveDataBus == null) {
            liveDataBus = new LiveDataBus();
        }
        return liveDataBus;
    }

    public <T> MutableLiveData<T> with(String key, Class<T> clazz) {
        if (!map.containsKey(key)) {
            objectMutableLiveData = new MutableLiveData<>();
            init(clazz);
            map.put(key, objectMutableLiveData);
        }
        return (MutableLiveData<T>) map.get(key);
    }

    private <T> void init(Class<T> clazz) {
        if (clazz.equals(String.class)) {
            objectMutableLiveData.setValue("");
        } else if (clazz.equals(Integer.class)) {
            objectMutableLiveData.setValue(0);
        } else if (clazz.equals(ArrayList.class)) {
            objectMutableLiveData.setValue(new ArrayList<>());
        } else if (clazz.equals(Boolean.class)) {
            objectMutableLiveData.setValue(false);
        }
    }
}
